package com.health.healthapplet.controller;

import com.health.healthapplet.entity.Response;
import com.health.healthapplet.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadFileController {
    @ResponseBody
    @PostMapping(value = "/health-service/upload")
    public Response upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        System.out.println(file);
        System.out.println(file.getContentType());
        System.out.println(file.getSize());
        String fileName = file.getOriginalFilename();
        fileName = FileUtils.renameToUUID(fileName);
        String[] strs = file.getContentType().split("/");
//        String filePath = strs[0].equals("image") || strs[0] == "image" ?
//                "/Users/wangxinpeng/work/muyuan/javaWork/healthapplet/src/main/resources/static/uploadImage/" :
//                "/Users/wangxinpeng/work/muyuan/javaWork/healthapplet/src/main/resources/static/uploadFile/";
        String filePath = strs[0].equals("image") || strs[0] == "image" ? "/uploadImage/" :
              "/uploadFile/";
//        251658240 240MB
        Response response = new Response();
        if(file.getSize()>251658240){
            return new Response("文件超出最大值",400,false);
        }else{
            try {
                FileUtils.uploadFile(file.getBytes(), filePath, fileName);
            } catch (Exception e) {
                return new Response("上传错误",400,false);
            }
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("fileName",fileName);
            dataMap.put("filePath",filePath+fileName);
            response.setResponse(true,"上传成功",200, dataMap);
            return response;
        }
    }
}
